package thread.matrix.individual;

import java.util.ArrayList;
import java.util.List;

/**
 * 并行的针对结果矩阵中每个元素一个线程的乘法器
 */
public class ParalleIndividualMultiplier {
    public static void multiply(double[][] matrix1,double[][] matrix2,double[][] result){
        List<Thread> threads = new ArrayList<>();
        for(int i=0;i<matrix1.length;i++){//matrix1的行数
            for(int j=0;j<matrix2[0].length;j++){//matrix2的列数
                //初始化结果矩阵
                result[i][j] = 0;
                for(int k=0;k<matrix2.length;k++){
                    //每个元素一个线程，计算结果矩阵的值
                    //创建线程
                    Thread t = new Thread(new IndividualMultiplierTask(matrix1,matrix2,result,i,j));
                    t.start();
                    threads.add(t);
                    if (threads.size()%10==0){
                        waitForThread(threads);
                    }
                }
            }
        }
    }

    private static void waitForThread(List<Thread> threads) {
        for (Thread t:threads){
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
